package com.sinodata.bsm.cicp.finder.tomcat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.JmxUtil;

public class TomcatGlobalRequestProcessor extends Finder {

    private static final Logger logger = Logger.getLogger(TomcatGlobalRequestProcessor.class);

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String port = (String) params.get("PORT");
        String name = null;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            ObjectName tomcatGlobalRequestProcessor = new ObjectName("Catalina:type=GlobalRequestProcessor,*");
            Set<ObjectName> set = connection.queryNames(tomcatGlobalRequestProcessor, null);
            for (ObjectName obj : set) {
                name = obj.getKeyProperty("name");
                String[] info = new String[4];
                list.add(info);
                info[0] = ip + "_tomcatManager_" + name;
                info[1] = "Cache." + name;
                info[2] = "Cache " + name;
                info[3] = name; //名称
            }
            return list;
        } catch (Exception e) {
            logger.error("failed to find Tomcat GlobalRequestProcessor: " + e);
            return null;
        } finally {
            JmxUtil.closeConnector(connector);
        }
    }
}